package com.zoffy.zoffyapi.service.impl.inner;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.zoffy.zoffyapi.exception.BusinessException;
import com.zoffy.zoffyapi.exception.ErrorCode;
import com.zoffy.zoffyapi.service.UserInterfaceInfoService;

import com.zoffy.zoffyapicommon.model.entity.UserInterfaceInfo;
import com.zoffy.zoffyapicommon.service.InnerUserInterfaceInfoService;
import jakarta.annotation.Resource;
import org.apache.dubbo.config.annotation.DubboService;
import org.redisson.Redisson;
import org.redisson.api.RLock;

@DubboService
public class InnerUserInterfaceInfoServiceImpl implements InnerUserInterfaceInfoService {
    @Resource
    UserInterfaceInfoService userInterfaceInfoService;
    @Resource
    private Redisson redisson;
    @Override
    public boolean handleInvoke(long userId,long interfaceId) {
        RLock lock = redisson.getLock(String.format("interface_count_%s_%s",userId,interfaceId));
        lock.lock();
        try{
            UserInterfaceInfo userInterfaceInfo = getUserInterfaceInfo(userId, interfaceId);
            if(userInterfaceInfo==null){
                throw new BusinessException(ErrorCode.PARAMS_ERROR);
            }
            Integer leftNum = userInterfaceInfo.getLeftNum();
            Integer totalNum = userInterfaceInfo.getTotalNum();
            if(leftNum<=0){
                throw new BusinessException(ErrorCode.FORBIDDEN_ERROR,"无调用次数");
            }
            UserInterfaceInfo newUserInterfaceInfo=new UserInterfaceInfo();
            newUserInterfaceInfo.setId(userInterfaceInfo.getId());
            newUserInterfaceInfo.setLeftNum(leftNum-1);
            newUserInterfaceInfo.setTotalNum(totalNum+1);
            userInterfaceInfoService.updateById(newUserInterfaceInfo);
            return true;
        }catch (Exception e){
            return false;
        }finally {
            lock.unlock();
        }}
    @Override
    public UserInterfaceInfo getUserInterfaceInfo(long userId, long interfaceId) {
        QueryWrapper<UserInterfaceInfo> queryWrapper=new QueryWrapper<>();
        queryWrapper.eq("user_id",userId);
        queryWrapper.eq("interface_info_id",interfaceId);
        return userInterfaceInfoService.getOne(queryWrapper);
    }
}
